<template>
  <div class="dashboard">
    <el-card class="welcome-card">
      <template #header>
        <div class="card-header">
          <span>欢迎使用健身房后台管理系统</span>
        </div>
      </template>
      <div class="welcome-content">
        <p>这是一个基于 Vue 3 + TypeScript + Vite + Element Plus 构建的后台管理系统。</p>
        <p>您可以在这里管理健身房的各项业务功能。</p>
      </div>
    </el-card>

    <!-- 数据概览 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon :size="30"><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ overview.totalMembers }}</div>
              <div class="stat-label">会员总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon :size="30"><Collection /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ overview.totalCourses }}</div>
              <div class="stat-label">课程总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon :size="30"><UserFilled /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ coachCount }}</div>
              <div class="stat-label">教练总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon :size="30"><Calendar /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ overview.todayBookings }}</div>
              <div class="stat-label">今日预约</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快捷操作 -->
    <el-card class="quick-actions-card">
      <template #header>
        <div class="card-header">
          <span>快捷操作</span>
        </div>
      </template>
      <div class="quick-actions">
        <el-button type="primary" @click="goTo('/member/list')">
          <el-icon><User /></el-icon>
          <span>添加会员</span>
        </el-button>
        <el-button type="success" @click="goTo('/course/list')">
          <el-icon><Collection /></el-icon>
          <span>添加课程</span>
        </el-button>
        <el-button type="warning" @click="goTo('/coach/list')">
          <el-icon><UserFilled /></el-icon>
          <span>添加教练</span>
        </el-button>
        <el-button type="danger" @click="goTo('/notification/announcement')">
          <el-icon><Bell /></el-icon>
          <span>发布公告</span>
        </el-button>
        <el-button @click="goTo('/review/reports')">
          <el-icon><Warning /></el-icon>
          <span>处理举报</span>
        </el-button>
        <el-button @click="goTo('/review/feedback')">
          <el-icon><Comment /></el-icon>
          <span>处理反馈</span>
        </el-button>
      </div>
    </el-card>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-section">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>会员增长趋势</span>
            </div>
          </template>
          <div ref="memberChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>收入统计</span>
            </div>
          </template>
          <div ref="revenueChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 重要信息提醒 -->
    <el-row :gutter="20" class="alerts-section">
      <el-col :span="12">
        <el-card class="alert-card">
          <template #header>
            <div class="card-header">
              <span>待处理事项</span>
            </div>
          </template>
          <div class="alerts">
            <div class="alert-item" @click="goTo('/review/reports')">
              <el-icon class="alert-icon" color="#e6a23c"><Warning /></el-icon>
              <div class="alert-content">
                <div class="alert-title">待处理举报</div>
                <div class="alert-count">{{ pendingReports }} 条</div>
              </div>
            </div>
            <div class="alert-item" @click="goTo('/review/feedback')">
              <el-icon class="alert-icon" color="#409eff"><Comment /></el-icon>
              <div class="alert-content">
                <div class="alert-title">待处理反馈</div>
                <div class="alert-count">{{ pendingFeedbacks }} 条</div>
              </div>
            </div>
            <div class="alert-item" @click="goTo('/review/course')">
              <el-icon class="alert-icon" color="#67c23a"><Star /></el-icon>
              <div class="alert-content">
                <div class="alert-title">待审核评价</div>
                <div class="alert-count">{{ pendingReviews }} 条</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="alert-card">
          <template #header>
            <div class="card-header">
              <span>系统通知</span>
            </div>
          </template>
          <div class="alerts">
            <div
              class="alert-item"
              v-for="notification in notifications"
              :key="notification.id"
              @click="markAsRead(notification.id)"
            >
              <el-icon class="alert-icon" :color="getNotificationColor(notification.type || 'OTHER')"
                ><Bell
              /></el-icon>
              <div class="alert-content">
                <div class="alert-title">{{ notification.title || '无标题' }}</div>
                <div class="alert-time">{{ formatTime(notification.createdAt) }}</div>
              </div>
            </div>
            <div class="alert-item" v-if="notifications.length === 0">
              <div class="alert-content">
                <div class="alert-title">暂无新通知</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import {
  User,
  Collection,
  UserFilled,
  Calendar,
  Bell,
  Warning,
  Comment,
  Star
} from '@element-plus/icons-vue'
import type { StatisticsOverview, MemberGrowthData, RevenueData } from '@/types/api/statistics'
import type { ReviewReport, Feedback } from '@/types/api/review'
import type { Notification } from '@/types/api/notification'
import { statisticsApi } from '@/api/modules/statistics'
import { reviewManagementApi, feedbackApi } from '@/api/modules/review'
import { notificationApi } from '@/api/modules/notification'

// 路由
const router = useRouter()

// 图表引用
const memberChartRef = ref<HTMLDivElement | null>(null)
const revenueChartRef = ref<HTMLDivElement | null>(null)
let memberChart: echarts.ECharts | null = null
let revenueChart: echarts.ECharts | null = null

// 数据概览
const overview = ref<StatisticsOverview>({
  totalMembers: 0,
  newMembers: 0,
  activeMembers: 0,
  totalCourses: 0,
  totalBookings: 0,
  todayBookings: 0,
  totalRevenue: 0,
  monthlyRevenue: 0,
  todayRevenue: 0,
  totalCheckins: 0,
  todayCheckins: 0,
  totalCards: 0,
  activeCards: 0
})

// 教练数量
const coachCount = ref<number>(0)

// 待处理事项
const pendingReports = ref<number>(0)
const pendingFeedbacks = ref<number>(0)
const pendingReviews = ref<number>(0)

// 系统通知
const notifications = ref<Notification[]>([])

// 获取数据统计概览
const getStatisticsOverview = async () => {
  try {
    const response = await statisticsApi.getStatisticsOverview()
    overview.value = response.data
  } catch (error) {
    ElMessage.error('获取数据统计概览失败')
  }
}

// 获取会员增长趋势数据
const getMemberGrowthData = async () => {
  try {
    const response = await statisticsApi.getMemberGrowthData({
      period: 'month'
    })

    // 修正：后端返回的数据结构是 { growth_data: [...], daily_avg: 0, total_new: 0, ... }
    // 需要访问 growth_data 属性，而不是直接访问 data
    const growthData = response.data.growth_data || []

    // 如果没有数据，显示空图表
    if (growthData.length === 0) {
      console.log('暂无会员增长数据')
    }

    // 准备图表数据
    const dates = growthData.map((item) => item.date)
    const counts = growthData.map((item) => item.count)

    // 渲染图表
    if (memberChartRef.value) {
      if (!memberChart) {
        memberChart = echarts.init(memberChartRef.value)
      }
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: counts,
            type: 'line',
            smooth: true,
            areaStyle: {},
            itemStyle: {
              color: '#67c23a'
            }
          }
        ]
      }
      memberChart.setOption(option)
    }
  } catch (error) {
    console.log('error:', error)
    ElMessage.error('获取会员增长趋势数据失败')
  }
}

// 获取收入统计数据
const getRevenueData = async () => {
  try {
    const response = await statisticsApi.getRevenueData({
      period: 'month'
    })
    console.log('response:', response)

    // 修正：后端返回的数据结构是 { trends: [...], summary: {...} }
    // 需要访问 trends 属性，而不是直接访问 data
    const trends = response.data.trends || []

    // 如果没有数据，显示空图表
    if (trends.length === 0) {
      console.log('暂无收入统计数据')
    }

    // 准备图表数据
    const dates = trends.map((item) => item.date)
    const amounts = trends.map((item) => item.amount)

    // 渲染图表
    if (revenueChartRef.value) {
      if (!revenueChart) {
        revenueChart = echarts.init(revenueChartRef.value)
      }
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: amounts,
            type: 'bar',
            itemStyle: {
              color: '#409eff'
            }
          }
        ]
      }
      revenueChart.setOption(option)
    }
  } catch (error) {
    console.log('error:', error)
    ElMessage.error('获取收入统计数据失败')
  }
}

// 获取教练数量（模拟数据）
const getCoachCount = () => {
  // 这里应该调用实际的API获取教练数量
  // 暂时使用模拟数据
  coachCount.value = 8
}

// 获取待处理举报数量
const getPendingReports = async () => {
  try {
    const response = await reviewManagementApi.getReviewReports({
      status: 'PENDING',
      page: 1,
      pageSize: 1
    })
    pendingReports.value = response.data.total
  } catch (error) {
    ElMessage.error('获取待处理举报数量失败')
  }
}

// 获取待处理反馈数量
const getPendingFeedbacks = async () => {
  try {
    const response = await feedbackApi.getAllFeedbackList({
      status: 'PENDING',
      page: 1,
      pageSize: 1
    })
    pendingFeedbacks.value = response.data.total
  } catch (error) {
    ElMessage.error('获取待处理反馈数量失败')
  }
}

// 获取待审核评价数量
const getPendingReviews = async () => {
  try {
    // 这里需要根据实际API调整，暂时用一个模拟值
    pendingReviews.value = 5
  } catch (error) {
    ElMessage.error('获取待审核评价数量失败')
  }
}

// 获取未读通知
const getUnreadNotifications = async () => {
  try {
    const response = await notificationApi.getNotificationList({
      isRead: false,
      page: 1,
      pageSize: 5
    })
    // 确保返回的是数组
    notifications.value = Array.isArray(response.data.list) ? response.data.list : []
  } catch (error) {
    console.log('error:', error)
    // 出错时设置为空数组，避免渲染错误
    notifications.value = []
    ElMessage.error('获取未读通知失败')
  }
}

// 标记通知为已读
const markAsRead = async (id: number) => {
  try {
    await notificationApi.markAsRead(id)
    // 重新获取通知列表
    getUnreadNotifications()
  } catch (error) {
    ElMessage.error('标记通知为已读失败')
  }
}

// 获取通知颜色
const getNotificationColor = (type: string) => {
  const colorMap: Record<string, string> = {
    COURSE: '#409eff',
    CARD: '#67c23a',
    SYSTEM: '#e6a23c',
    OTHER: '#909399'
  }
  return colorMap[type] || '#409eff'
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '-'
  try {
    return new Date(time).toLocaleDateString()
  } catch (error) {
    console.log('formatTime error:', error)
    return '-'
  }
}

// 跳转到指定路径
const goTo = (path: string) => {
  router.push(path)
}

// 初始化所有数据
const initAllData = async () => {
  await Promise.all([
    getStatisticsOverview(),
    getMemberGrowthData(),
    getRevenueData(),
    getPendingReports(),
    getPendingFeedbacks(),
    getPendingReviews(),
    getUnreadNotifications()
  ])
  // 获取教练数量
  getCoachCount()
}

// 窗口大小改变时重绘图表
const handleResize = () => {
  if (memberChart) memberChart.resize()
  if (revenueChart) revenueChart.resize()
}

// 初始化
onMounted(() => {
  initAllData()
  window.addEventListener('resize', handleResize)
})

// 渲染图表
nextTick(() => {
  if (memberChartRef.value) {
    memberChart = echarts.init(memberChartRef.value)
  }
  if (revenueChartRef.value) {
    revenueChart = echarts.init(revenueChartRef.value)
  }
})
</script>

<style scoped lang="scss">
.dashboard {
  .welcome-card {
    margin-bottom: 20px;

    .card-header {
      font-size: 18px;
      font-weight: 600;
    }

    .welcome-content {
      p {
        margin: 10px 0;
        font-size: 16px;
        line-height: 1.6;
      }
    }
  }

  .stats-row {
    margin-bottom: 20px;

    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;

        .stat-icon {
          margin-right: 15px;
          color: $primary-color;
        }

        .stat-info {
          .stat-number {
            font-size: 24px;
            font-weight: 600;
            color: #333;
          }

          .stat-label {
            font-size: 14px;
            color: #666;
          }
        }
      }
    }
  }

  .quick-actions-card {
    margin-bottom: 20px;

    .quick-actions {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;

      .el-button {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 12px 20px;

        .el-icon {
          margin-right: 5px;
        }
      }
    }
  }

  .chart-section {
    margin-bottom: 20px;

    .chart-card {
      .card-header {
        font-size: 16px;
        font-weight: 600;
      }

      .chart-container {
        height: 300px;
      }
    }
  }

  .alerts-section {
    .alert-card {
      .card-header {
        font-size: 16px;
        font-weight: 600;
      }

      .alerts {
        .alert-item {
          display: flex;
          align-items: center;
          padding: 15px 0;
          border-bottom: 1px solid #eee;
          cursor: pointer;
          transition: background-color 0.3s;

          &:last-child {
            border-bottom: none;
          }

          &:hover {
            background-color: #f5f7fa;
          }

          .alert-icon {
            font-size: 20px;
            margin-right: 15px;
          }

          .alert-content {
            flex: 1;

            .alert-title {
              font-size: 14px;
              font-weight: 500;
              color: #333;
              margin-bottom: 5px;
            }

            .alert-count,
            .alert-time {
              font-size: 12px;
              color: #999;
            }
          }
        }
      }
    }
  }
}
</style>
